<template>
  <el-dialog :title="title" :model-value="visible" width="800px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input v-model="form.deviceCode" placeholder="请输入设备编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备ICCID" prop="iccid">
            <el-input v-model="form.iccid" placeholder="请输入设备ICCID" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="产品" prop="productId">
            <el-select v-model="form.productId" placeholder="请选择产品" clearable filterable @change="handleProductChange">
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.name"
                :value="product.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { DeviceFormData } from '@/api/IOT/deviceManage/types'
import type { ProductInfo } from '@/api/IOT/protocolManage/productManage/types'


// Props
interface Props {
  visible: boolean
  title: string
  formData: DeviceFormData | null
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  title: '',
  formData: () => ({})
})

// Emits
const emit = defineEmits(['update:visible', 'submit', 'cancel'])

// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
  id: '',
  deviceCode: '',
  iccid: '',
  productId: '',
  productName: '',
  status: 1,
  remark: ''
})

// 产品列表
const productList = ref<ProductInfo[]>([])

// 表单验证规则
const rules = reactive({
  deviceCode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  iccid: [{ required: true, message: '设备ICCID不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})

// 监听表单数据变化
watch(() => props.formData, (newVal) => {
  if (newVal) {
    Object.assign(form, newVal)
    // 如果有产品ID但没有产品名称，从产品列表中获取
    if (newVal.productId && !newVal.productName && productList.value.length > 0) {
      const selectedProduct = productList.value.find(p => p.id === newVal.productId)
      if (selectedProduct) {
        form.productName = selectedProduct.name
      }
    }
  }
}, { deep: true, immediate: true })

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (!newVal) {
    resetForm()
  }
})

// 监听产品列表变化，用于编辑时设置产品名称
watch(() => productList.value, () => {
  if (props.formData?.productId && !form.productName && productList.value.length > 0) {
    const selectedProduct = productList.value.find(p => p.id === props.formData.productId)
    if (selectedProduct) {
      form.productName = selectedProduct.name
    }
  }
}, { immediate: true })

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      emit('submit', { ...form })
    }
  })
}

// 取消
const handleCancel = () => {
  emit('cancel')
  emit('update:visible', false)
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
}

// 本地虚拟延迟（随机不超过1.5s）
const delayRandom = (min = 300, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 获取产品列表（本地写死 + 虚拟请求）
const getProducts = async () => {
  try {
    await delayRandom()
    productList.value = [
      { id: 'P-1001', name: '水质监测设备' } as ProductInfo,
      { id: 'P-1002', name: '泵站控制器' } as ProductInfo,
      { id: 'P-1003', name: '压力传感器' } as ProductInfo,
      { id: 'P-1004', name: '流量计' } as ProductInfo
    ]
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  }
}

// 产品选择变化处理
const handleProductChange = (productId: string) => {
  const selectedProduct = productList.value.find(p => p.id === productId)
  if (selectedProduct) {
    form.productName = selectedProduct.name
  } else {
    form.productName = ''
  }
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: '',
    deviceCode: '',
    iccid: '',
    productId: '',
    productName: '',
    status: 1,
    remark: ''
  })
}

// 组件挂载时获取产品列表
onMounted(() => {
  getProducts()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>